﻿/* SharePoint Console Project
 * Http://SharePointConsole.codeplex.com
 * Copyright Jean-Alain Baeyens (2009)
 * Software under Microsoft Reciprocal License (Ms-RL)
 */

using System;

using Microsoft.SharePoint;
using Microsoft.Office.Server.Search.Administration;
using Sharepoint.Console.Commands;

namespace Sharepoint.Console.Search
{
    class MapManagedProperty : BaseCommande
    {
        public override string ShortHelp
        {
            get
            {
                return "Map a managed property";
            }
        }

        public override string LongHelp
        {
            get
            {
                return "Map an existing crawled property to an existing managed property.";
            }
        }


        public override string Syntax
        {
            get
            {
                return "MapManagedProperty 'ManagedPropertyName' 'CrawledPropertyName'";
            }
        }

        public override string Execute(string[] args)
        {
            if (args.Length != 3) return string.Format("Invalide syntax. Use {0}", Syntax);
            if (args.Length != 3) return "Invalid number of parameters. Syntax: MapManagedProperty 'ManagedPropertyName' 'CrawledPropertyName'";
            
            try
            {
                string crawledPropertyName = args[2];
                string managedPropertyName = args[1];

                Schema spSchema = new Schema(SearchContext.GetContext(this.SharepointConnection.Site));
                ManagedPropertyCollection properties = spSchema.AllManagedProperties;

                ManagedProperty property = properties[managedPropertyName]; 
                MappingCollection crawledProperties = property.GetMappings();

                SharepointHelper helper = new SharepointHelper();
                CrawledProperty cprop = helper.GetCrawledProperty(this.SharepointConnection, crawledPropertyName);

                if (cprop != null)
                {
                    Mapping map = new Mapping(cprop.Propset
                                             , cprop.Name
                                             , cprop.VariantType
                                             , property.PID);
                    crawledProperties.Add(map);

                    property.SetMappings(crawledProperties);
                    // Reset property to include the CrawledProperty in index.
                    cprop.IsMappedToContents = true;
                    cprop.Update();

                    return "Property mapped";
                }
                else
                {
                    return "Crawled property doesn't exist";
                }
            }
            
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
